package cn.acewill.yxd.yunxundian.ui.follow_up;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.zyf.vc.ui.PlayVideoActiviy;
import com.zyf.vc.ui.RecorderActivity;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.photoCrop.BitmapUtils;
import cn.acewill.yxd.yunxundian.componet.photoCrop.PopupUtil;
import cn.acewill.yxd.yunxundian.pubClass.MyFragmentAdapter;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.follow_up.nodeStruct.FU_row;
import cn.acewill.yxd.yunxundian.utils.PermissionUtil;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;


@ContentView(R.layout.activity_follow_up_item)
public class FollowUpItemActivity extends BaseActivity implements FollowUpItemFragment.AddMediaListener {
    public static final String TAG = "FollowUpItemActivity";
    public static final String []sTitle = new String[]{"问题分析","行动计划","整改结果"};
    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    @ViewInject(R.id.container)
    private ViewPager mViewPager;
    @ViewInject(R.id.tabs)
    private TabLayout mTabLayout;
    @ViewInject(R.id.textTitle)
    private TextView mTitle;
    private FU_row node;
    private FollowUpItemFragment resultFragment;
    private int tabIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        mTitle.setText("问题详情");
        node = (FU_row) getIntent().getSerializableExtra("node");
        tabIndex = getIntent().getIntExtra("tabIndex",0);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null){
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initView() {
        mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[0]));
        mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[1]));
        mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[2]));

        mTabLayout.setupWithViewPager(mViewPager);
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(FollowUpItemFragment.newInstance(FollowUpItemFragment.FOLLOW_UP_ITEM, node));
        fragments.add(FollowUpItemFragment.newInstance(FollowUpItemFragment.FOLLOW_UP_ITEM_PLAN, node));
        resultFragment = FollowUpItemFragment.newInstance(FollowUpItemFragment.FOLLOW_UP_ITEM_RESULT, node);
        resultFragment.setAddMediaListener(this);
        fragments.add(resultFragment);

        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),fragments, Arrays.asList(sTitle));
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(tabIndex);
        getVideoPath();
    }

    //showPop
    Dialog popDialog;
    ProgressDialog waterDialog;
    private StringBuilder allMediaString = new StringBuilder();

    boolean isMultiSelector=true;
    final int REQUEST_CODE_GALLERY=1000;
    final  int REQUEST_CODE_CARMEAR=1001;
    final int REQUEST_TAKE_VIDEO_CODE =1002 ;
    private Handler mHandler = new iHandler(this);

    @Override
    public void showPop(int type, StringBuilder allMediaString){
        this.allMediaString = allMediaString;
        LayoutInflater inflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (inflater!=null){
            int viewId = type==FollowUpItemFragment.PHOTO?R.layout.view_popup_button:R.layout.view_popup_button2;
            View holder = inflater.inflate(viewId,
                    (ViewGroup) getWindow().getDecorView(),false);
                    //:inflater.inflate(R.layout.view_popup_button2,null,false);
            ButtonClick click = new ButtonClick();
            if(type==FollowUpItemFragment.PHOTO){
                View gallery = holder.findViewById(R.id.btnPhoto);
                View capture = holder.findViewById(R.id.btnCapture);
                View cancel = holder.findViewById(R.id.btnCanel);
                gallery.setOnClickListener(click);
                capture.setOnClickListener(click);
                cancel.setOnClickListener(click);
            }else{
                View cancle=holder.findViewById(R.id.btnCanel);
                View video=holder.findViewById(R.id.btnVideo);
                cancle.setOnClickListener(click);
                video.setOnClickListener(click);
            }
            popDialog = PopupUtil.makePopup(this, holder);
            popDialog.show();
        }
    }

    public class ButtonClick implements View.OnClickListener{
        @Override
        public void onClick(View v) {

            if (popDialog!=null){
                popDialog.dismiss();
            }

            if (v.getId() == R.id.btnPhoto) {// 图库选取
                checkTakeMediaPermission(R.id.btnPhoto);
            }

            if (v.getId() == R.id.btnCapture) {// 拍照
                checkTakeMediaPermission(R.id.btnCapture);
            }

            if (v.getId() == R.id.btnVideo){//视频录制
                checkTakeMediaPermission(R.id.btnVideo);
            }
        }
    }

    private void checkTakeMediaPermission(int typeid) {
        int permissionState_Camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int permissionState_Storage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionState_Audio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (permissionState_Camera != PackageManager.PERMISSION_GRANTED || permissionState_Storage != PackageManager.PERMISSION_GRANTED
                || permissionState_Audio != PackageManager.PERMISSION_GRANTED) {
            // 用户已经拒绝过一次，给用户解释提示对话框
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                // 展示自定义提醒框
                new MaterialDialog.Builder(this)
                        .content("你必须允许相应权限")
                        .positiveText("确定")
                        .positiveColor(getResources().getColor(R.color.blue))
                        .negativeText("取消")
                        .negativeColor(getResources().getColor(R.color.color_theme))
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                PermissionUtil.requestPermissionForCamera(FollowUpItemActivity.this);
                            }

                        })
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .build()
                        .show();
            }else{
                PermissionUtil.requestPermissionForCamera(this);
            }
        }else{
            if(typeid==R.id.btnVideo)
                skipToVideoTaker();
            else if(typeid==R.id.btnCapture) {
                YXDAPP.GallerySet(getSelectJpgCount(),this);
                GalleryFinal.openCamera(REQUEST_CODE_CARMEAR, YXDAPP.functionConfig, myResultCallBack);
            }
            else if(typeid==R.id.btnPhoto)
            {
                if (isMultiSelector){
                    YXDAPP.GallerySet(getSelectJpgCount(),this);
                    GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }else{ //选取头像
                    if (getSelectJpgCount()==0){
                        Toast.makeText(this,"选取的照片达到最大数量,长按可删除照片",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, YXDAPP.functionConfig,myResultCallBack);
                }
            }
        }
    }
    /*跳转到拍摄*/
    private void skipToVideoTaker(){
        startActivityForResult(new Intent(this, RecorderActivity.class),REQUEST_TAKE_VIDEO_CODE);
    }
    /*计算选取的照片的额数量*/
    public int getSelectJpgCount(){
        if (TextUtils.isEmpty(allMediaString)){
            return 9;
        }
        String[] array = allMediaString.toString().split(",");
        if (array.length<9){
            return 9-array.length;
        }else{
            return 0;
        }

    }

    private GalleryFinal.OnHanlderResultCallback myResultCallBack=new GalleryFinal.OnHanlderResultCallback() {

        @Override
        public void onHanlderSuccess(int reqeustCode, final List<PhotoInfo> resultList) {

            waterDialog=new ProgressDialog(FollowUpItemActivity.this);
            waterDialog.setMessage("图片处理中，请稍后");
            waterDialog.show();
            Thread t=new Thread(String.valueOf(Looper.getMainLooper())){
                @Override
                public void run() {
                    for (int i=0;i<resultList.size();i++) {
                        String path = resultList.get(i).getPhotoPath();
                        WindowManager winManager = getWindowManager();
                        DisplayMetrics metrics = new DisplayMetrics();
                        winManager.getDefaultDisplay().getMetrics(metrics);
                        Bitmap mBitmap = BitmapUtils.getBmpFromFile(path,
                                metrics.widthPixels, metrics.heightPixels, null);
                        try {
                            mBitmap.compress(Bitmap.CompressFormat.JPEG, 60, new FileOutputStream(path));
//                            int width = mBitmap.getWidth();
//                            int height = mBitmap.getHeight();
                            //加水印后的bitmap
                            //   Bitmap cropBitmap=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
                            // mBitmap = creatBitmap(mBitmap);
                            mBitmap=creatMyBitmap(mBitmap);
                            //将图片保存在本地指定路径
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
                            Random random = new Random();
                            String fileName2 = String.valueOf(random.nextInt(Integer.MAX_VALUE));
                            String resultPath = pubClass.pictureSavePath + "yxd" + sdf.format(new Date()) + fileName2 + ".jpg";
                            //流保存
                            File file = new File(resultPath);
                            FileOutputStream outputStream = null;
                            try {
                                outputStream = new FileOutputStream(file);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
                            try {
                                if (outputStream!=null){
                                    outputStream.flush();
                                    outputStream.close();
                                    mBitmap.recycle();
                                }
                                //保存图片后发送广播通知更新数据库
                                Uri uri = Uri.fromFile(file);
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                allMediaString.append(resultPath).append(",");

                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    Message msg=new Message();
                    msg.what=0;
                    mHandler.sendMessage(msg);

                }
            };
            t.start();

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(FollowUpItemActivity.this,"图片获取失败",Toast.LENGTH_SHORT).show();
        }
    };

    public static class iHandler extends Handler {

        private WeakReference<FollowUpItemActivity> mActivity;
        iHandler(FollowUpItemActivity activity){
            mActivity = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                //图片水印完毕
                mActivity.get().waterDialog.dismiss();
                mActivity.get().deleteDir();
                if(mActivity.get().resultFragment!=null){
                    mActivity.get().resultFragment.setMediaListViewData(FollowUpItemFragment.PHOTO, mActivity.get().allMediaString);
                }
            }
        }
    }

    public Bitmap creatMyBitmap(Bitmap src){
//        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        int WW = metrics.widthPixels;
//        int WH = metrics.widthPixels;
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAlpha(60);
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap newBit=Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBit);
        canvas.drawBitmap(src,0,0,null);
        //创建一个矩形，将文字放入矩形中
        RectF rect=new RectF(30,h-160,450,h-30);
        canvas.drawRoundRect(rect,30,30,paint);
        //绘制文字
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setTextSize(36);
        paint.setAntiAlias(true);
        String date= BaseActivity.getNowDate();
        canvas.drawText(date,60,h-110,paint);
        canvas.drawText(node.shopName,60,h-65,paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newBit;
    }

    public void deleteDir(){
        //文件路径
        String path= Environment.getExternalStorageDirectory()+"/DCIM"+"/GalleryFinal";
        File file=new File(path);
        if (!file.exists() || !file.isDirectory()){
            return;
        }
        for (File dir:file.listFiles()){
            if (dir.isFile()){
                dir.delete();
            }else if (dir.isDirectory()){
                //递归删除
                deleteDir();
            }
            //删除目录
            file.delete();
        }
    }

    public void getVideoPath() {
        PlayVideoActiviy.setOnPickFinishListener(new PlayVideoActiviy.PickFinishListener() {
            @Override
            public void onPickFinish(String path) {
                BaseActivity.showAnimaDialog(FollowUpItemActivity.this,"视频保存在"+"\n"+path);
                allMediaString.append(path).append(",");
                if(resultFragment!=null)
                    resultFragment.setMediaListViewData(FollowUpItemFragment.VIDEO, allMediaString);
            }
        });
    }
}
